<template>
  <el-dialog
    title="批量修改商品"
    :visible.sync="visible"
    width="600px">
    <div class="dialog-form">
      <div class="ml-20 mb-20 ta-r">
        <el-button icon="el-icon-download" size="small" @click="downloadTemplate">下载模板</el-button>
      </div>
      <div class="pd-20 bd-r-2 ta-c"
        v-loading="uploading"
        element-loading-text="上传解析中...">
        <el-upload
          :file-list="fileList"
          class="upload-demo"
          accept=".xls,.xlsx"
          drag
          action="#"
          :limit="1"
          :http-request="handleUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>修改</div>
          <div class="el-upload__tip" slot="tip">只能上传 xls/xlxs 格式文件</div>
        </el-upload>
      </div>

      <el-alert
        :closable="false"
        v-show="errorMsg"
        :title="errorMsg"
        type="error">
      </el-alert>
    </div>
  </el-dialog>
</template>

<script>
import {downloadTemplate} from '@/util/file'
import {
  uploadSkuExcel
} from "@/api/commodityfiles";

export default {
  data() {
    return {
      visible: false,
      fileList: [],
      errorMsg: '',
      uploading: false,
    }
  },
  methods: {
    show() {
      this.visible = true
      this.init()
    },
    init() {
      this.fileList = []
      this.errorMsg = ''
    },
    downloadTemplate() {
      downloadTemplate('批量修改商品模板.xlsx')
    },
    handleUpload(params) {
      this.errorMsg = ''
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('files', params.file)
        this.uploading = true
        uploadSkuExcel(formData).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '批量修改成功！'
            })
            this.$emit('editSuccess')
            this.visible = false
          } else {
            this.$message({
              type: 'error',
              message: '批量修改失败！'
            })
          }
          resolve()
        }).catch(err => {
          this.errorMsg = err.message
          reject()
        }).finally(() => {
          this.uploading = false
        })
      })
    }
  },
  created() {

  }
}
</script>

<style lang="scss" scoped>
.dialog-form {

}
</style>
